package com.braveman.im.application;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Vibrator;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.braveman.im.http.HeadInterceptor;
import com.braveman.im.service.LocationService;
import com.braveman.im.ui.weiget.DemoHelper;
import com.ht.baselibs.application.HTApplication;
import com.ht.baselibs.retrofit.RequestUtils;
import com.ht.baselibs.retrofit.converter.fastjson.FastJsonResponseBodyConverter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseUI;
import com.braveman.im.constant.HttpConfig;
import com.braveman.im.service.PushService;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.vondear.rxtools.RxTool;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import cn.magicwindow.MWConfiguration;
import cn.magicwindow.MagicWindowSDK;
import cn.magicwindow.Session;

public class AppApplication extends HTApplication {
    public static HashMap<String, Object> tempMap;
    // 记录是否已经初始化
    private boolean isInit = false;
    // 上下文菜单
    private Context mContext;
    public LocationService locationService;
    public Vibrator mVibrator;
    private static AppApplication instance;


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install((this));
        Session.setAutoSession(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
// queryAndLoadNewPatch不可放在attachBaseContext 中，否则无网络权限，建议放在后面任意时刻，如onCreate中
        //友盟分享
        Config.DEBUG = true;
        UMShareAPI.get(this);
        Intent downloadIntent = new Intent(this, PushService.class);
        this.startService(downloadIntent);
        tempMap = new HashMap<>();
        MobclickAgent.setCatchUncaughtExceptions(IS_DEBUG_MODE);
        //SpeechUtility.createUtility(this, SpeechConstant.APPID + "=586db9ce");
        instance = this;

//           RequestUtils.initInterceptors(new ConsultInterceptor(), new ParameterInterceptor());
        RequestUtils.initInterceptors(new HeadInterceptor());
        mContext = this;
        EaseUI.getInstance().init(getContext(), null);
//        DemoHelper.getInstance().init(this);
        // 初始化环信SDK
        initEasemob();
        // 初始化
        // 开启log
        if (isDebugMode()) {
//            Router.openLog();
        }
//初始化RXTool
        RxTool.init(this);
        /***
         * 初始化定位sdk，建议在Application中创建
         */
        locationService = new LocationService(getApplicationContext());
        mVibrator = (Vibrator) getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
//        SDKInitializer.initialize(getApplicationContext());
        MWConfiguration config = new MWConfiguration(this);
        config.setLogEnable(true);//打开魔窗Log信息
        MagicWindowSDK.initSDK(config);
        //友盟配置
        {
            //各个平台的配置，建议放在全局Application或者程序入口
            PlatformConfig.setQQZone("1106341078", "EK61VRyE4fb0Aa2l");
//        PlatformConfig.setWeixin("wx9a1cbbc9c5b82eb7", "18973c9f67fa80a4b5df8d456b4dc019");
            PlatformConfig.setWeixin("wx6d8778370b81a2f1", "4211c51437f89f1bcb3280e25b8b7fab");

        }
    }

    @Override
    protected boolean isDebugMode() {
        return true;
    }

    @Override
    protected String getHost() {
        return HttpConfig.BASE_URL;
    }

    @Override
    protected FastJsonResponseBodyConverter.DecodeService getDecodeService() {
        return null;
    }

    public static Object getTempData(String key) {
        return tempMap.get(key);
    }

    public static void putTempData(String key, Object value) {
        tempMap.put(key, value);
    }

//    IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
//    MyBroadcastReceiver receiver = new MyBroadcastReceiver();
//    registerReceiver(receiver, filter);

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        String versioncode = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            versioncode = pi.versionCode + "";
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    /**
     *
     */
    private void initEasemob() {
        // 获取当前进程 id 并取得进程名
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        /**
         * 如果app启用了远程的service，此application:onCreate会被调用2次
         * 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
         * 默认的app会在以包名为默认的process name下运行，如果查到的process name不是app的process name就立即返回
         */
        if (processAppName == null || !processAppName.equalsIgnoreCase(mContext.getPackageName())) {
            // 则此application的onCreate 是被service 调用的，直接返回
            return;
        }
        if (isInit) {
            return;
        }
        /**
         * SDK初始化的一些配置
         * 关于 EMOptions 可以参考官方的 API 文档
         * http://www.easemob.com/apidoc/android/chat3.0/classcom_1_1hyphenate_1_1chat_1_1_e_m_options.html
         */
        EMOptions options = new EMOptions();
        // 设置Appkey，如果配置文件已经配置，这里可以不用设置
        // options.setAppKey("guaju");
        // 设置自动登录
        options.setAutoLogin(true);
        // 设置是否需要发送已读回执
        options.setRequireAck(true);
        // 设置是否需要发送回执，TODO 这个暂时有bug，上层收不到发送回执
        options.setRequireDeliveryAck(true);
        // 设置是否需要服务器收到消息确认
//        options.setRequireServerAck(true);
        // 收到好友申请是否自动同意，如果是自动同意就不会收到好友请求的回调，因为sdk会自动处理，默认为true
        options.setAcceptInvitationAlways(false);
        // 设置是否自动接收加群邀请，如果设置了当收到群邀请会自动同意加入
        options.setAutoAcceptGroupInvitation(false);
        // 设置（主动或被动）退出群组时，是否删除群聊聊天记录
        options.setDeleteMessagesAsExitGroup(false);
        // 设置是否允许聊天室的Owner 离开并删除聊天室的会话
        options.allowChatroomOwnerLeave(true);
        // 设置google GCM推送id，国内可以不用设置
        // options.setGCMNumber(MLConstants.ML_GCM_NUMBER);
        // 设置集成小米推送的appid和appkey
        // options.setMipushConfig(MLConstants.ML_MI_APP_ID, MLConstants.ML_MI_APP_KEY);

        // 调用初始化方法初始化sdk
        EMClient.getInstance().init(mContext, options);

        // 设置开启debug模式
        EMClient.getInstance().setDebugMode(true);

        // 设置初始化已经完成
        isInit = true;
    }

    private String getAppName(int pid) {
        String processName = null;
        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List list = activityManager.getRunningAppProcesses();
        Iterator i = list.iterator();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pid) {
                    // 根据进程的信息获取当前进程的名字
                    processName = info.processName;
                    // 返回当前进程名
                    return processName;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 没有匹配的项，返回为null
        return null;
    }


    public static AppApplication getInstance() {
        return instance;
    }

}
